#include "cMaterial.h"

#include <cassert>
#include <fstream>
#include <sstream>

#include "../util/logger.h"

ShiftEngine::cMaterial::cMaterial( cTexturePtr diffuseTex /*= 0*/, 
								  cTexturePtr normalTex /*= 0*/, 
								  cTexturePtr specularTex /*= 0*/ )
	: useDiffuseTex(diffuseTex != 0), useNormalTex(normalTex != 0), useSpecularTex(specularTex != 0),
	diffuseTexture(diffuseTex), normalTexture(normalTex), specularTexture(specularTex)
{
}

ShiftEngine::cMaterial::~cMaterial()
{
}

void ShiftEngine::cMaterial::SetNormalTexture( cTexturePtr normalTex )
{
	useNormalTex = normalTex != 0;
	this->normalTexture = normalTex;
}

void ShiftEngine::cMaterial::SetDiffuseTexture( cTexturePtr diffureTex )
{
	this->useDiffuseTex = diffureTex != 0;
	this->diffuseTexture = diffureTex;
}

void ShiftEngine::cMaterial::SetSpecularTexture( cTexturePtr specularTex )
{
	this->useSpecularTex = specularTex != 0;
	this->specularTexture = specularTex;
}

cTexturePtr ShiftEngine::cMaterial::GetNormalTexture() const
{
	return normalTexture;
}

cTexturePtr ShiftEngine::cMaterial::GetDiffuseTexture() const
{
	return diffuseTexture;
}

cTexturePtr ShiftEngine::cMaterial::GetSpecularTexture() const
{
	return specularTexture;
}

bool ShiftEngine::cMaterial::UsesNormalTexture() const
{
	return useNormalTex;
}

bool ShiftEngine::cMaterial::UsesDiffuseTexture() const
{
	return useDiffuseTex;
}

bool ShiftEngine::cMaterial::UsesSpecularTexture() const
{
	return useSpecularTex;
}

//////////////////////////////////////////////////////////////////////////

ShiftEngine::cMaterialManager::cMaterialManager(cTextureManager * textureMgr)
	: pTextureMgr(textureMgr)
{
}

ShiftEngine::cMaterialManager::~cMaterialManager()
{
}

ShiftEngine::cMaterialPtr ShiftEngine::cMaterialManager::LoadMaterial( const std::wstring & filename )
{
	auto iter = materials.find(filename);

	if(iter != materials.end())
		return iter->second;

	//loading material here
	bool use_diff = false, use_normal = false, use_spec = false;
	std::wstring buffer;
	std::wifstream input(filename);
	std::wstringstream stream;

	if(input.fail())
		MainLog.Error(true, L"Unable to load material: " + filename);
	std::getline(input, buffer);
	//UNDONE: doesn't work
	static_assert(false, "Undone method!");
	cMaterialPtr mat(new cMaterial());
}

void ShiftEngine::cMaterialManager::CheckMaterials()
{
	for(auto iter = materials.begin(); iter != materials.end(); iter++)
	{
		if(iter->second.use_count() == 1)
		{
			iter = this->materials.erase(iter);
		}
	}
}
